package com.hakgc.rent.web.servlet;

import com.hakgc.rent.entity.User;
import com.hakgc.rent.exception.LoginException;
import com.hakgc.rent.service.UserService;
import com.hakgc.rent.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.net.URLDecoder;

/**
 * @author Xing.Jiejian
 * @date 2020/11/17
 */
@WebServlet(name = "LoginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String name = request.getParameter("name");
        String password = request.getParameter("password");

        // 校验用户是否登录成功
        UserService userService = new UserServiceImpl();
        User user = null;
        try {
            user = userService.login(name,password);
        } catch (LoginException e) {
            // 登录失败
            e.printStackTrace();
            request.setAttribute("errorMsg",e.getMessage());
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            return;
        }
        // 如果设置了“记住我”，则将用户名将用户名存储到cookie中，下次访问登录页直接填写用户名
        if ("remember-me".equals(request.getParameter("remember"))){
            Cookie cookie = new Cookie("username", name);
            //设置路径，这个路径即该工程下都可以访问该cookie 如果不设置路径，那么只有设置该cookie路径及其子路径可以访问
            cookie.setPath("/");
            //设置cookie生命周期，单位s
            cookie.setMaxAge(60 * 60);
            response.addCookie(cookie);
        }

        // 登录成功，将用户放入session作用域，重定向到首页
        HttpSession session = request.getSession();
        session.setAttribute("currentUser",user);
        response.sendRedirect(request.getContextPath()+"/index.jsp");

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 进入登录页面
        // 从cookie中判断获取是否有保存的用户名
        Cookie[] cookies = request.getCookies();
        if (cookies!=null){
            for (Cookie cookie : cookies) {
                // 获取到用户名，将用户名放入作用域中
                if ("username".equals(cookie.getName())){
                    request.setAttribute("username", URLDecoder.decode(cookie.getValue(),"utf-8"));
                    break;
                }
            }
        }
        request.getRequestDispatcher("/login.jsp").forward(request,response);

    }
}
